package com.xbq.oauth.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.PanelUI;
import java.io.IOException;
import java.util.Random;

@RestController
@RequestMapping("/code")
@Slf4j
public class ValidateCodeController {


    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    public static final String SMS_SESSION_KEY = "SESSION_KEY_SMS_CODE";

    //SpringSecurity提供的操作Session工具
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();


    /**
     * 获取图片验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //step1；生成一个随机数
        String validCode = getRandomNumber(4);
        //step2：将随机数放入session
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,validCode);
        log.info("图片验证码为：" + validCode);
        //step3：
    }




    @GetMapping("/sms")
    public void smsCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //step1；生成一个短信验证码
        String validCode = getRandomNumber(4);
        //step2：将短信验证码放入session
        sessionStrategy.setAttribute(new ServletWebRequest(request),SMS_SESSION_KEY,validCode);
        log.info("短信验证码为：" + validCode);
        //step3：

    }



    private String getRandomNumber(int length){
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0 ; i < length ; i++){
            int value = random.nextInt(10);
            sb.append(value);
        }

        return sb.toString();
    }



}
